package com.qing.common.view;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.qing.common.R;
import com.qing.common.adpter.PhotoPreviewAdapter;
import com.qing.common.base.BaseActivity;
import com.qing.common.databinding.ActivityPhotoPreviewBinding;
import com.qing.common.util.TransitionAnimationUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class PhotoPreviewActivity extends BaseActivity<ActivityPhotoPreviewBinding> {

    public static final String PREFIX_SHARED_IMAGE = "shared_image";
    public static final String PREFIX_EXTRAS = "com.qing.common.view.PhotoPreviewActivity.";
    public static final String EXTRAS_IMAGE_RESOURCES = PREFIX_EXTRAS + "images";
    private static final String TAG = "PhotoPreviewActivity";
    private PhotoPreviewAdapter mAdapter;

    /**
     * 启动图片预览页面并添加共享元素过渡动画
     *
     * @param activity 宿主Activity（不可为空）
     * @param view     共享元素视图（不可为空），用于实现平滑的转场动画
     * @param url      待预览图片的网络地址（不可为空）
     *                 <p>
     *                 实现逻辑：
     *                 1. 基于图片URL生成唯一共享元素名称（格式：shared_image_哈希值）
     *                 2. 构建包含图片元数据的Data对象（包含URL和共享元素名称）
     *                 3. 通过startActivityInner执行实际跳转，添加共享元素过渡动画
     */
    public static void startActivity(@NonNull Activity activity, @NonNull View view, @NonNull String url) {
        String sharedElementName = PREFIX_SHARED_IMAGE + "_" + url.hashCode();
        startActivityInner(activity, new PhotoPreviewAdapter.Data(url, 0, sharedElementName), view, sharedElementName);
    }

    /**
     * 启动图片预览页面并添加共享元素过渡动画
     *
     * @param activity   宿主Activity（不可为空）
     * @param view       共享元素视图（不可为空），用于实现平滑的转场动画
     * @param resourceId 资源id
     *                   <p>
     *                   实现逻辑：
     *                   1. 基于图片资源Id生成唯一共享元素名称（格式：shared_image_id）
     *                   2. 构建包含图片元数据的Data对象（包含资源Id和共享元素名称）
     *                   3. 通过startActivityInner执行实际跳转，添加共享元素过渡动画
     */
    public static void startActivity(@NonNull Activity activity, @NonNull View view, int resourceId) {
        String sharedElementName = PREFIX_SHARED_IMAGE + "_" + resourceId;
        startActivityInner(activity, new PhotoPreviewAdapter.Data(null, resourceId, sharedElementName), view, sharedElementName);
    }

    /**
     * 启动图片预览Activity，并设置共享元素过渡动画
     *
     * @param activity    源Activity上下文，用于启动新Activity
     * @param views       需要进行共享元素过渡的视图数组
     * @param resourceIds 每个视图对应的图片资源ID数组，与views数组长度必须一致
     * @throws IllegalArgumentException 当views和resourceIds数组长度不一致时抛出
     */
    @SuppressWarnings("unchecked")
    public static void startActivity(@NonNull Activity activity, @NonNull View[] views, @NonNull int[] resourceIds) {
        // 校验视图数组与资源ID数组长度一致性
        if (views.length != resourceIds.length) {
            throw new IllegalArgumentException("views.length != resourceIds.length");
        }

        // 准备共享元素集合和图片数据数组
        List<Pair<View, String>> sharedElements = new ArrayList<>();
        PhotoPreviewAdapter.Data[] photos = new PhotoPreviewAdapter.Data[views.length];

        // 遍历视图数组构建共享元素名称和图片数据
        for (int i = 0; i < views.length; i++) {
            // 生成唯一共享元素名称：前缀 + 资源ID
            String sharedElementName = PREFIX_SHARED_IMAGE + "_" + resourceIds[i];
            sharedElements.add(Pair.create(views[i], sharedElementName));

            // 构建图片数据对象
            PhotoPreviewAdapter.Data photoData = new PhotoPreviewAdapter.Data();
            photoData.setResId(resourceIds[i]);
            photoData.setSharedElementName(sharedElementName);
            photos[i] = photoData;
        }

        // 转换共享元素集合为数组，并启动内部Activity
        Pair<View, String>[] elements = sharedElements.toArray(new Pair[0]);
        startActivityInner(activity, photos, elements);
    }


    private static void startActivityInner(@NonNull Activity activity, @NonNull PhotoPreviewAdapter.Data data, @NonNull View view, String sharedElementName) {
        Intent intent = new Intent(activity, PhotoPreviewActivity.class);
        intent.putExtra(EXTRAS_IMAGE_RESOURCES, new PhotoPreviewAdapter.Data[]{data});
        ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(activity, view, sharedElementName);
        activity.startActivity(intent, options.toBundle());
    }

    @SafeVarargs
    private static void startActivityInner(@NonNull Activity activity, PhotoPreviewAdapter.Data[] data, @NonNull Pair<View, String>... sharedElements) {
        Intent intent = new Intent(activity, PhotoPreviewActivity.class);
        intent.putExtra(EXTRAS_IMAGE_RESOURCES, data);
        ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(activity, sharedElements);
        activity.startActivity(intent, options.toBundle());
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setTheme(R.style.PhotoPreview);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected ActivityPhotoPreviewBinding createViewBinding() {
        return ActivityPhotoPreviewBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initView() {
        mAdapter = new PhotoPreviewAdapter(null);
        getBinding().vpImages.setAdapter(mAdapter);
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
        Intent intent = getIntent();
        Parcelable[] parcelables = intent.getParcelableArrayExtra(EXTRAS_IMAGE_RESOURCES);
        if (parcelables != null) {
            List<PhotoPreviewAdapter.Data> list = Arrays.stream(parcelables).map(PhotoPreviewAdapter.Data.class::cast).collect(Collectors.toList());
            if (!list.isEmpty()) {
                getBinding().vpImages.setTransitionName(list.get(0).getSharedElementName());
                getBinding().vpImages.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                    @Override
                    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                        getBinding().vpImages.removeOnLayoutChangeListener(this);
                        getBinding().vpImages.setTransitionName("");
                    }
                });
            }
            mAdapter.setData(list);
        }
    }

    @Override
    protected void initListener() {
        getBinding().getRoot().post(() -> {
            if (mAdapter.getRecyclerView() != null) {
                mAdapter.getRecyclerView().addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener() {

                    @Override
                    public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                        if (e.getAction() == MotionEvent.ACTION_DOWN) {
                            animateToolBar(!(getBinding().clToolBar.getVisibility() == View.VISIBLE));
                        }
                        return super.onInterceptTouchEvent(rv, e);
                    }
                });
            }
        });
        getBinding().ivBack.setOnClickListener(v -> {
            finishAfterTransition();
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getBinding().getRoot().post(() -> animateToolBar(true));
    }

    private void animateToolBar(boolean show) {
        TransitionAnimationUtils.INSTANCE.applyExplodeTransition(getBinding().getRoot());
        getBinding().clToolBar.setVisibility(show ? View.VISIBLE : View.GONE);
    }
}
